<?php
/* 
* @Title:  [商品搜索控制器]
* @Author: {chenlei} [chenleib5@126.com]
* @Date:   2014-04-15 10:35:50
* @Last Modified by:   Administrator
* @Last Modified time: 2014-04-21 09:19:02
* @Copyright:  [hn7m.com]
*/
class SearchControl extends CommonControl{
	public $goodsModel=NULL;

	public function __init(){
		parent::__init();
		$this->goodsModel=K('Goods');
	}
	/**
	 * [index 显示搜索结果]
	 * @return [type] [description]
	 */
	public function index(){
		if(IS_POST){
			$keyword=Q('post.keyword','','htmlspecialchars');
			//如果不输入关键词,则出来全部商品
			if(empty($keyword)){
				$search=$this->goodsModel->get_data(array('gid','gname','gpmt_price','gplace','gthumb_img'),$where=NULL,'gsort ASC');
				$this->assign('test',1);
			}else{
				//规定用户还可以按空格/中英文逗号/的来搜索,例如:好看 女装;
				$searchBar=array(' ',',','，','的');
				foreach ($searchBar as $n) {
					$tempArr[]=explode($n, $keyword);
				}
				foreach ($tempArr as $key => $value) {
					foreach ($value as $v) {
						$arr[]=$v;
					}
				}
				$arr=array_unique($arr);
				foreach ($arr as $key => $value) {
					$tempArr[$key]=trim($value);
				}
				$keyword=array();
				//防止用户输入N多个空格,例如好看       女装;
				foreach ($arr as $key => $value) {
					if(empty($value)) continue;
					$keyword[]=$value;
				}
				$search=array();
				foreach ($keyword as $key => $value) {
					$data=$this->goodsModel->get_data(array('gid','gname','gpmt_price','gplace','gthumb_img'),"gis_shelves=1 AND gname like '%$value%' OR gkeywords like '%$value%'",'gsort ASC');
					if($data){
						$search=array_merge($search,$data);
					}
				}
				
				//加搜索词的高亮效果
				//原创设计个性<span class="highlight" style="color:red">围巾</span>丝巾纯棉蓝色条纹口袋款限量男女通用款
				foreach ($search as $key => $value) {
					foreach ($keyword as $k => $v) {
						$replace="<span class='highlight' style='color:red'>$v</span>";
						$search[$key]['gname']=str_ireplace($v, $replace, $value['gname']);
					}	
				}
			}
			if(!empty($search)){
				$search=array_unique_fb($search);  //自定义的函数,放在Common/Lib/functions.php
			}
            $n=count($search);
            $this->assign('num',$n);
			$this->assign('search',$search);
		}
		//分配热门商品推荐
		$hot=$this->goodsModel->get_data(array('gid','gone_words','gpmt_price','gplace','gthumb_img'),$where=NULL,'gsort ASC');
		foreach ($hot as $key => $value) {
			if(empty($value['gone_words'])) continue;
			$temp[]=$value;
		}
		$this->assign('hot',$temp);
		$this->display();
	}
}
?>